import { configureStore, Action, getDefaultMiddleware } from "@reduxjs/toolkit"
import { useDispatch } from "react-redux"
import { ThunkAction } from "redux-thunk"

import rootReducer, { RootState } from "reducers"

import {
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER
} from "redux-persist"
// import storage from "redux-persist/lib/storage"
import storage from "redux-persist/lib/storage/session"

const persistConfig = {
  key: "root",
  version: 1,
  storage
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

// https://redux-toolkit.js.org/usage/usage-guide
const store = configureStore({
  reducer: persistedReducer,
  middleware: getDefaultMiddleware({
    serializableCheck: {
      ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER]
    }
  })
})

export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch()
export type AppThunk = ThunkAction<void, RootState, unknown, Action>

export default store
